#include <iostream>
#include <string>

struct ListNode
{
    int val;
    ListNode *next;
    // 链表结构体初始化
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        ListNode *result = nullptr;
        ListNode *current;
        int num = 0;
        while (l1 && l2)
        {
            num = l1->val + l2->val + num;
            ListNode *node = new ListNode(num % 10);
            num = num / 10;
            result ? current->next = node : result = node;
            current = node;
            l1 = l1->next;
            l2 = l2->next;
        }
        if (l2)
        {
            l1 = l2;
        }
        while (l1)
        {
            num = l1->val + num;
            ListNode *node = new ListNode(num % 10);
            num = num / 10;
            /*
            三元条件运算符     条件：result
            result !=nullptr   current->next = node
            result ==nullptr   result = node  该节点是链表表头赋值
            */
            result ? current->next = node : result = node;
            current = node;
            l1 = l1->next;
        }
        if (num)
        {
            ListNode *node = new ListNode(num % 10);
            current->next = node;
            current = node;
        }
        return result;
    }
};

int main(int argc, char **argv)
{
    ListNode l9(9);
    ListNode l8(9, &l9);
    ListNode l7(9, &l8);
    ListNode l6(9, &l7);
    ListNode l5(9, &l6);
    ListNode l4(9, &l5);
    ListNode l3(9, &l4);
    ListNode l2(9, &l3);
    ListNode l1(9, &l2);

    ListNode r4(9);
    ListNode r3(9, &r4);
    ListNode r2(9, &r3);
    ListNode r1(9, &r2);

    ListNode *result = Solution().addTwoNumbers(&l1, &r1);
    while (result)
    {
        std::cout << result->val << " ";
        result = result->next;
    }
    std::cout << std::endl;

    return 0;
}
